import { fileURLToPath, URL } from "node:url";
import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueDevTools from "vite-plugin-vue-devtools";

// element-plus 按需导入
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

// 新增插件
import { createHtmlPlugin } from "vite-plugin-html";
import viteCompression from "vite-plugin-compression";

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量 - 修正：使用 process.cwd() 而不是 import.meta.url
  const env = loadEnv(mode, process.cwd(), '');

  return {
    plugins: [
      vue(),
      // 根据环境条件启用开发工具
      mode === 'development' ? vueDevTools() : null,
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [
          ElementPlusResolver({
            importStyle: "sass"
          })
        ],
      }),
      // 新增HTML插件
      createHtmlPlugin({
        minify: mode === 'production', // 仅生产环境压缩HTML
        inject: {
          data: {
            title: env.VITE_APP_TITLE || '籍祥供应链系统'
          }
        }
      }),
      // 新增压缩插件
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240, // 10KB以上才压缩
        algorithm: 'gzip',
        ext: '.gz'
      })
    ].filter(Boolean), // 过滤掉null的插件

    // 构建配置
    build: {
      // 生产环境移除console和debugger
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: mode === 'production', // 生产环境移除console
          drop_debugger: true // 始终移除debugger
        },
        format: {
          comments: mode !== 'production' // 非生产环境保留注释
        }
      },

      // 代码分割优化
      rollupOptions: {
        output: {
          manualChunks: {
            'vue-vendor': ['vue', 'vue-router', 'pinia'],
            'element-ui': ['element-plus'],
            'utils-vendor': ['axios', 'lodash-es']
          },
          chunkFileNames: `assets/[name]-[hash].js`,
          entryFileNames: `assets/[name]-[hash].js`,
          assetFileNames: `assets/[name]-[hash].[ext]`
        }
      },

      // 生成sourcemap（生产环境不生成）
      sourcemap: mode !== 'production'
    },

    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
      },
    },

    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/element/index.scss" as *;`,
        },
      },
    },

    // 服务器配置 - 完全使用环境变量
    server: {
      host: '0.0.0.0',
      port: 3000,
      proxy: env.VITE_API_BASE_URL ? {
        '/api': {
          target: env.VITE_API_BASE_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      } : undefined
    },

    // 预览配置
    preview: {
      port: 4173,
      host: '0.0.0.0'
    }
  };
});
